﻿namespace Digitalmes.Application.Sys.Users.Queries;

/// <summary>
/// 验证用户账号，若未找到用户或账户密码不匹配，则返回 (false, default），其中会返回结果会包含用户拥有的角色集合
/// </summary>
/// <param name="Username"></param>
public record ValidateAndGetUserQuery(string Username, string Password) : IRequest<(bool ok, SysUserDto? user)>;

internal sealed class ValidateAndGetUserQueryHandler(IRepository<SysUser> repo) : IRequestHandler<ValidateAndGetUserQuery, (bool, SysUserDto?)>
{
    public async Task<(bool, SysUserDto?)> Handle(ValidateAndGetUserQuery request, CancellationToken cancellationToken)
    {
        var user = await repo.AsQueryable()
            .Includes(m => m.UserRoles, it => it.Role)
            .FirstOrDefaultAsync(s => s.Username == request.Username, cancellationToken);

        if (user == null ||
            user.Status == EnabledStatusEnum.Disabled ||
            CryptoUtils.MDString(request.Password) != user.Password)
        {
            return (false, default);
        }

        return (true, user.Adapt<SysUserDto>());
    }
}
